package com.smfx.yxt.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smfx.yxt.model.ParentInfo;
import com.smfx.yxt.service.IParentService;
import com.smfx.yxt.utils.HkFaceUtil;

@Component
public class FacePersonJob {
	
	private Logger logger = LoggerFactory.getLogger(FacePersonJob.class);
	
	@Autowired
	private IParentService parentService;
	
	@Scheduled(cron = "0 0 0/12 * * ? ")
	public void batchUpdatePersonId() {
		try {
			int count = parentService.selectNoPersonIdCount();
			if(count > 0) {
				int pageNo = 1;
				int pageSize = 500;
				String result = HkFaceUtil.getPersonInfosByPage(1, 500);
				JSONObject json = JSONObject.parseObject(result);
				if("0".equals(json.getString("code"))) {
					JSONObject data = json.getJSONObject("data");
					JSONArray array = data.getJSONArray("list");
					int total = data.getIntValue("total");
					batchUpdate(array);
					while (pageNo * pageSize < total) {
						pageNo += 1;
						queryData(pageNo, pageSize);
					}
				}
			}
		} catch (Exception e) {
			logger.error("---getPersonId error={}", e);
		}
	}
	
	private void queryData(int pageNo, int pageSize) {
		String result = HkFaceUtil.getPersonInfosByPage(pageNo, pageSize);
		JSONObject json = JSONObject.parseObject(result);
		if("0".equals(json.getString("code"))) {
			JSONObject data = json.getJSONObject("data");
			JSONArray array = data.getJSONArray("list");
			batchUpdate(array);
		}
	}
	
	private void batchUpdate(JSONArray array) {
		List<ParentInfo> list = new ArrayList<>();
		for(int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			String jobNo = json.getString("jobNo");
			if(jobNo.indexOf("JZ") != -1) {
				try {
					ParentInfo parent = new ParentInfo();
					parent.setId(Integer.valueOf(jobNo.substring(jobNo.indexOf("JZ")+2, jobNo.length())));
					parent.setFacePersonId(json.getString("personId"));
					list.add(parent);
				} catch (Exception e) {
					logger.error("--get jobNo={}, error={}", jobNo, e.getMessage());
				}
			}
		}
		if(list.size() > 0) {
			parentService.updateBatchPersonId(list);
		}
	}
}
